from django.db.models import Count
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from artmarket.models import Order, Artwork


class OrderMaterialStatisticView(APIView):
    def get(self, request):
        all_materials = Artwork.objects.values_list('material', flat=True).distinct().order_by('material')
        material_order = Order.objects.values('artwork__material') \
            .annotate(usage_count=Count('buyer')).order_by('-usage_count')

        # 将统计结果转换为字典，便于查找
        material_order_dict = {data['artwork__material']: data['usage_count'] for data in material_order}
        # 构建响应数据
        response_data = []
        for material in all_materials:
            response_data.append({
                'material': material,
                'usage_count': material_order_dict.get(material, 0)  # 如果没有该材质的订单，则默认为0
            })
        return Response(data={'data': response_data}, status=status.HTTP_200_OK)
